<template>
    <List border size="small" class="list-product">
        <Row slot="header">
            <Col span="1">序号</Col>
            <Col span="3">产品代码</Col>
            <Col span="6">产品名称</Col>
            <Col span="3">数量</Col>
            <Col span="3">单价</Col>
            <Col span="3">失效日期</Col>
            <Col span="3">总毛重</Col>
            <Col span="2">操作</Col>
        </Row>
        <ListItem v-if="products.length === 0" class="no-products">
            <div>请添加产品</div>
        </ListItem>
        <ListItem v-for="(item, index) in products" :key="index">
            <Row :gutter="10" class="list-item-row">
                <Col span="1" class="list-item-col">{{index+1}}</Col>
                <Col span="3" :title="item.sku" class="list-item-col">{{item.sku}}</Col>
                <Col span="6" class="ellipsis list-item-col" :title="item.product.name">{{item.product.name}}</Col>
                <Col span="3">
                    <FormItem :label-width="0"
                              :rules="ruleValidate.quantity"
                              :prop="`products.${index}.quantity`">
                        <Input number size="small" v-model="products[index].quantity"></Input>
                    </FormItem>
                </Col>
                <Col span="3">
                    <FormItem :label-width="0"
                              :rules="ruleValidate.price"
                              :prop="`products.${index}.price`">
                        <Input number size="small" v-model="products[index].price"></Input>
                    </FormItem>
                </Col>
                <Col span="3">
                    <FormItem :label-width="0"
                              :rules="ruleValidate.lot"
                              :prop="`products.${index}.lot`">
                        <DatePicker type="date" size="small" v-model="products[index].lot"
                                    @on-change="(val)=> products[index].lot = val"></DatePicker>
                    </FormItem>
                </Col>
                <Col span="3" class="list-item-col">
                    <div :title="`${item.quantity}*${item.product.weight}`">{{(item.quantity *
                        item.product.weight).toLocaleString()}}
                    </div>
                </Col>
                <Col span="2" class="list-item-col">
                    <Button type="error" size="small" @click="deleteProduct(index)">删除</Button>
                </Col>
            </Row>
        </ListItem>

        <Row slot="footer">
            <Col span="10">
                <FormItem prop="products" :label-width="0" :rules="ruleValidate.products"></FormItem>
                <ButtonGroup>
                    <Button size="small" @click="openComponent('IChooseProduct', {products})">添加商品
                    </Button>
                    <Button size="small" @click="openComponent('ProductImport', {products})">导入商品
                    </Button>
                </ButtonGroup>
            </Col>
            <Col span="3">数量:{{total.quantity.toLocaleString()}}</Col>
            <Col span="6">总价:{{total.price.toLocaleString()}}</Col>
            <Col span="5">总毛重:{{total.weight.toLocaleString()}}</Col>
        </Row>


        <component v-if="componentProps.value" :is="componentProps.view" v-model="componentProps.value"
                   :props="componentProps.props"
                   @on-product-choose="productChoose"></component>
    </List>
</template>

<script>

    import IChooseProduct from "./chooseProduct";
    import ProductImport from "./import";

    const floatObj = () => {
        function isInteger(obj) {
            return Math.floor(obj) === obj
        }

        function toInteger(floatNum) {
            let ret = {times: 1, num: 0};
            if (isInteger(floatNum)) {
                ret.num = floatNum;
                return ret
            }
            let strfi = floatNum + '';
            let dotPos = strfi.indexOf('.');
            let len = strfi.substr(dotPos + 1).length;
            let times = Math.pow(10, len);
            let intNum = parseInt(floatNum * times + 0.5, 10);
            ret.times = times;
            ret.num = intNum;
            return ret
        }

        function operation(a, b, op) {
            let o1 = toInteger(a);
            let o2 = toInteger(b);
            let n1 = o1.num;
            let n2 = o2.num;
            let t1 = o1.times;
            let t2 = o2.times;
            let max = t1 > t2 ? t1 : t2;
            let result = null;
            switch (op) {
                case 'add':
                    if (t1 === t2) { // 两个小数位数相同
                        result = n1 + n2
                    } else if (t1 > t2) { // o1 小数位 大于 o2
                        result = n1 + n2 * (t1 / t2)
                    } else { // o1 小数位 小于 o2
                        result = n1 * (t2 / t1) + n2
                    }
                    return result / max;
                case 'subtract':
                    if (t1 === t2) {
                        result = n1 - n2
                    } else if (t1 > t2) {
                        result = n1 - n2 * (t1 / t2)
                    } else {
                        result = n1 * (t2 / t1) - n2
                    }
                    return result / max;
                case 'multiply':
                    result = (n1 * n2) / (t1 * t2);
                    return result;
                case 'divide':
                    result = (n1 / n2) * (t2 / t1);
                    return result
            }
        }

        function add(a, b) {
            return operation(a, b, 'add')
        }

        function subtract(a, b) {
            return operation(a, b, 'subtract')
        }

        function multiply(a, b) {
            return operation(a, b, 'multiply')
        }

        function divide(a, b) {
            return operation(a, b, 'divide')
        }

        // exports
        return {
            add: add,
            subtract: subtract,
            multiply: multiply,
            divide: divide
        }
    };

    import IContentMixins from "../../../mixins/iContentMixins";
    import IDrawerMixins from "../../../mixins/iDrawerMixins";

    export default {
        name: "ProductShowList",
        components: {IChooseProduct, ProductImport},
        mixins: [IContentMixins, IDrawerMixins],
        props: {
            value: {
                type: Array
            }
        },
        data() {
            return {
                products: [],
                ruleValidate: {
                    products: [
                        {type: 'array', required: true, message: '至少选择一个产品'}
                    ],
                    quantity: [
                        {type: 'integer', required: true, message: '数量必须填写'},
                        {type: 'integer', min: 1, message: '数量不能小于1'},
                    ],
                    price: [
                        {type: 'number', required: true, message: '单价必须填写'},
                        {
                            type: 'number', validator: (rule, value) => {
                                if (value <= 0) {
                                    return new Error('单价不能小于或等于0');
                                }
                                return true;
                            }
                        }
                    ]
                }
            }
        },
        computed: {
            total() {
                let quantity = 0, price = 0, weight = 0;

                this.products.forEach((item) => {
                    quantity = floatObj().add(quantity, item.quantity);
                    price = floatObj().add(price, floatObj().multiply(item.price, item.quantity));
                    weight = floatObj().add(weight, floatObj().multiply(item.product.weight, item.quantity));
                });
                return {
                    quantity, price, weight
                }
            }
        },
        methods: {
            deleteProduct(index) {
                this.products.splice(index, 1);
                this.emitProduct();
            },
            productChoose(val) {
                let index = this.products.findIndex((item) => item.sku === val.sku);
                if (index === -1) {
                    this.products.push({
                        sku: val.sku,
                        quantity: 0,
                        price: 0,
                        lot: null,
                        name: val.name,
                        product: val
                    });
                }
                this.emitProduct();
            },
            emitProduct() {
                this.$emit('input', this.products);
            }
        },
        watch: {
            value(val) {
                val.forEach((item) => {
                    item.sku = item.product.sku;
                });
                this.products = val
            }
        }
    }
</script>

<style scoped lang="less">
    .no-products {
        color: #c3cbd6;
        text-align: center;
        background-color: #f8f8f9;

        div {
            width: 100%;
        }
    }

    .list-header-right {
        text-align: right;
    }

    .ivu-form-item {
        margin-bottom: 0;
    }

    .list-header {
        border-bottom: 1px solid #e8eaec;
    }

    .list-item-row {
        width: 100%;
    }

    .list-product {
        margin-bottom: 20px;

        .list-item-row {
            .list-item-col {
                line-height: 32px;
            }
        }
    }
</style>
